// 路由拦截 权限

import router from '@/router'
import store from '@/store'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

const whiteList = ['/login', '/404']
// 前置守卫
router.beforeEach(async (to, from, next) => {

    Nprogress.start() //开启进度条
    // console.log(to.path, from.path);
    if (store.getters.token) {
        if (to.path === '/login') {
            next('/')
        } else {
            if (!store.getters.userId) {
                // 没有用户资料 menus 用户权限标识
                const { roles: { menus } } = await store.dispatch('user/getUserInfo')
                // console.log(menus);
                // routes 当前用户所拥有的动态路由权限
                const routes = await store.dispatch('permission/filterRoutes', menus)
                // 将当前的动态路由加到当前的路由规则上
                router.addRoutes([...routes,{ path: '*', redirect: '/404', hidden: true }])
                next(to.path) // 解决直接执行next()时的异常
            }else{
                next()
            }   
        }
    } else {
        if (whiteList.indexOf(to.path) > -1) {
            next()
        } else {
            next('/login')
        }
    }
    Nprogress.done() // 解决手动输入地址进度条不关闭

})



router.afterEach(() => {
    Nprogress.done()
})